package com.tepth.busfix.main.chooseoperator;

import android.content.Intent;
import android.support.v4.util.LongSparseArray;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.tepth.busfix.R;
import com.tepth.busfix.adapter.JobContentAdapter;
import com.tepth.busfix.adapter.TroubleSuggestTypeAdapter;
import com.tepth.busfix.base.BaseActivity;
import com.tepth.busfix.bean.reponse.Process;
import com.tepth.busfix.bean.reponse.ProcessDecorate;
import com.tepth.busfix.bean.reponse.TroubleClassification;
import com.tepth.busfix.bean.reponse.TroubleSuggestSection;
import com.tepth.busfix.bean.reponse.TroubleType;
import com.tepth.busfix.config.SpKey;
import com.tepth.busfix.data.DataProvider;
import com.tepth.busfix.tools.SPUtils;
import com.tepth.busfix.view.dialog.DialogDelegate;
import com.tepth.busfix.view.dialog.SweetAlertDialogDelegate;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by pc on 2017/3/16.
 */

public class ChooseOperatorActivity extends BaseActivity
        implements ChooseOperatorContract.View {
    public static final int RESULT_CODE = 1;
    public static final String EXTRA_NAME = "list";
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.recycler_view_trouble)
    RecyclerView recyclerViewTrouble;
    @BindView(R.id.recycler_view_suggest)
    RecyclerView recyclerViewSuggest;
    JobContentAdapter jobContentAdapter;
    DialogDelegate dialogDelegate;
    private ChooseOperatorPresenter mPresenter;
    private ChooseOperatorModel mModel;

    @Override
    public void onNetworkError(String msg) {
        dialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onError(String msg) {
        dialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onTokenInvalid(String msg) {
        dialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_choose_operator;
    }

    @Override
    public void initView() {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        tvTitle.setText(R.string.common_trouble_suggest);
        dialogDelegate = new SweetAlertDialogDelegate(this);
        ArrayList<TroubleClassification> troubleClassificationArrayList =
                DataProvider.getClassificatons();
        if (troubleClassificationArrayList.isEmpty()) {
            mPresenter.getTroubleClassification();
            dialogDelegate.showProgressDialog(true, getString(R.string._loading));
        } else {
            showTroubleClassifications(DataProvider.getFilterClassifications());
        }
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_save:
                        onReturn();
                        break;
                }
                return true;
            }
        });
    }

    @Override
    public void setPresenter() {
        mPresenter = new ChooseOperatorPresenter();
        mModel = new ChooseOperatorModel();
        mPresenter.setVM(this, mModel);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onReturn();
                break;
        }
        return true;
    }

    private void onReturn() {
        setIntentData();
        finish();
    }

    private void setIntentData() {
        Intent intent = new Intent();
        int typeSize = typeLongSparseArray.size();
        for (int i = 0; i < typeSize; i++) {
            TroubleType troubleType = typeLongSparseArray.valueAt(i);
            troubleType.setHasSelected(false);
        }
        int processSize = mSelectedSuggestArray.size();
        ArrayList<ProcessDecorate> arrayList = new ArrayList<>();
        for (int i = 0; i < processSize; i++) {
            ProcessDecorate processDecorate = mSelectedSuggestArray.valueAt(i);
            processDecorate.getProcess().setChecked(false);
            arrayList.add(processDecorate);
        }
        intent.putExtra(EXTRA_NAME, arrayList);
        setResult(RESULT_CODE, intent);
    }

    @Override
    public String getAuthKey() {
        return SPUtils.getString(this, SpKey.KEY_AUTH_KEY, "");
    }

    //记录type选中个数
    private LongSparseArray<Integer> sparseIntArray = new LongSparseArray<>();
    //记录选中type
    private LongSparseArray<TroubleType> typeLongSparseArray = new LongSparseArray<>();
    //已选的操作项
    LongSparseArray<ProcessDecorate> mSelectedSuggestArray = new LongSparseArray<>();

    @Override
    public void setTroubleClassifications(List<TroubleClassification> list) {
        if (list == null) {
            return;
        }
        DataProvider.setClassificatons((ArrayList<TroubleClassification>) list);
        showTroubleClassifications(DataProvider.getFilterClassifications());
        dialogDelegate.clearDialog();
    }

    private void showTroubleClassifications(List<TroubleClassification> list) {
        List<TroubleSuggestSection> sections = new ArrayList<>();
        for (TroubleClassification troubleClassification : list) {
            List<TroubleType> troubleTypes = troubleClassification.getListTroubleType();
            if (troubleTypes != null && !troubleTypes.isEmpty()) {
                for (TroubleType troubleType : troubleTypes) {
                    troubleType.setParentId(troubleClassification.getId());
                    troubleType.setParentName(troubleClassification.getName());
                }
                TroubleSuggestSection headSection = new TroubleSuggestSection(true,
                        troubleClassification.getName());
                TroubleSuggestSection listSection = new TroubleSuggestSection(troubleTypes);
                sections.add(headSection);
                sections.add(listSection);
            }
        }
        recyclerViewTrouble.setLayoutManager(new LinearLayoutManager(this));
        final TroubleSuggestTypeAdapter typeAdapter = new TroubleSuggestTypeAdapter(this, R.layout.item_repair_content,
                R.layout.item_repair_head, sections, new TroubleSuggestTypeAdapter.OnTagClickListener() {
            @Override
            public void onTagClick(TroubleType troubleType) {
                jobContentAdapter.setNewData(troubleType.getListProcess());
                jobContentAdapter.setTroubleType(troubleType);
            }
        });
        recyclerViewTrouble.setAdapter(typeAdapter);

        recyclerViewSuggest.setLayoutManager(new LinearLayoutManager(this));
        jobContentAdapter = new JobContentAdapter(this, R.layout.item_job_content, new ArrayList<Process>());
        recyclerViewSuggest.setAdapter(jobContentAdapter);
        recyclerViewSuggest.addOnItemTouchListener(new OnItemClickListener() {

            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Process process = jobContentAdapter.getItem(position);
                process.setChecked(!process.isChecked());
                jobContentAdapter.notifyItemChanged(position);

                TroubleType troubleType = jobContentAdapter.getTroubleType();
                long troubleTypeId = troubleType.getId();
                long troubleParentTypeId = troubleType.getParentId();
                Integer integer = sparseIntArray.get(troubleTypeId);
//                if (process.isChecked()) {
//                    mSelectedSuggestArray.put(process.getId(),
//                            new ProcessDecorate(troubleTypeId, troubleParentTypeId, process));
//                    if (integer != null) {
//                        sparseIntArray.put(troubleTypeId, integer + 1);
//                    } else {
//                        sparseIntArray.put(troubleTypeId, 1);
//                    }
//                    typeLongSparseArray.put(troubleTypeId, troubleType);
//                } else {
//                    mSelectedSuggestArray.remove(process.getId());
//                    sparseIntArray.put(troubleTypeId, integer - 1);
//                }

                if (sparseIntArray.get(troubleTypeId) > 0) {
                    troubleType.setHasSelected(true);
                } else {
                    troubleType.setHasSelected(false);
                    typeLongSparseArray.remove(troubleTypeId);
                }
                typeAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.save, menu);
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            onReturn();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }
}
